package com.qf.service.impl;

import com.qf.constant.CacheConstants;
import com.qf.constant.StrategyConstants;
import com.qf.feign.CacheService;
import com.qf.model.StandardSubmit;
import com.qf.service.StrategyService;
import com.qf.util.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 5分钟限流策略
 * @author lenovo
 * @version V1.0
 * @Date 2021/11/22 21:37
 */
@Component(value = "limitFiveMinutes")
@Slf4j
public class LimitFiveMinutesFilterServiceImpl implements StrategyService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private PushMsgUtil pushMsgUtil;

    @Override
    public Boolean execute(StandardSubmit standardSubmit) {
        log.info("【策略模块 - 1分钟限流策略】开始执行，短信对象内容 standardSubmit={}",standardSubmit);
        Integer clientID = standardSubmit.getClientID();
        //一分钟
        long ttl = 60;
        //获取生存时间内发送短信的次数
        String size = cacheService.get(CacheConstants.CACHE_PREFIX_SMS_LIMIT + clientID);

        if (StringUtils.isEmpty(size)){
            //还没有发送过，或者已经过了1分钟
            cacheService.set(CacheConstants.CACHE_PREFIX_SMS_LIMIT + clientID, "1",ttl);
            log.info("【策略模块 - 1分钟限流策略】发送成功！ standardSubmit={}",standardSubmit);
            return true;
        }

        Integer sizeInt = Integer.parseInt(size);
        //已经发送过，判断发送次数是否大于10
        if (sizeInt >= 10){
            //发送次数已经大于10那么限流
            log.info("【策略模块 - 1分钟限流策略】发送失败，短信发送次数过多，限流 standardSubmit={}",standardSubmit);
            pushMsgUtil.pushReport(standardSubmit, StrategyConstants.STRATEGY_ERROR_LIMIT);
            pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_LIMIT);
            return false;
        }else {
            //发送次数小于10可以正常发送，发送次数加一
            cacheService.incr(CacheConstants.CACHE_PREFIX_SMS_LIMIT + clientID,1);
            log.info("【策略模块 - 1分钟限流策略】发送成功！ standardSubmit={}",standardSubmit);
            return true;
        }

    }
}
